package com.xbx.admin.filter;


import com.google.gson.Gson;
import com.xbx.baseweb.model.User;
import com.xbx.common.constant.GlobalConstant;
import com.xbx.common.utils.DESEncryptUtils;
import com.xbx.admin.annotation.UserInfoContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 获取用户信息过滤器
 *
 * @author 89005691
 * @create 2018-10-08 15:08
 */
@Slf4j
public class TransmitUserInfoFilter implements Filter {

    @Value("${userInfoDesKey}")
    private String userInfoDesKey;

    public TransmitUserInfoFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        this.initUserInfo((HttpServletRequest) request);
        chain.doFilter(request, response);
    }

    private void initUserInfo(HttpServletRequest request) {
        String userJson = request.getHeader(GlobalConstant.GLOBAL_USER_INFO);
        if (StringUtils.isNotBlank(userJson)) {
            try {

                userJson = DESEncryptUtils.decrypt(userJson, userInfoDesKey);
                User user = new Gson().fromJson(userJson, User.class);
                //将user放入上下文中
                UserInfoContext.setUser(user);

                log.info("获取到用户信息{}", user.getUsername());
            } catch (Exception e) {
                log.error("获取用户信息出错", e);
            }
        }
    }

    @Override
    public void destroy() {
    }
}
